package com.chenfan.magic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.chenfan.common.vo.UserVO;
import com.chenfan.magic.config.UserVoConstextHolder;
import com.chenfan.magic.constant.MagicConstant;
import com.chenfan.magic.entity.vo.FieldVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author liuming
 * @date 2021-05-12 14:34
 */
@Component
public class FieldHandleComponent {

    @Autowired
    @Qualifier("redisTemplate2")
    private RedisTemplate redisTemplate2;

    public String getList(HttpServletRequest request) {
        String url = request.getParameter(MagicConstant.URL);
        String key = getKey(url);
        String value = (String) redisTemplate2.opsForValue().get(key);
        return value;
    }

    public void saveFields(HttpServletRequest request, FieldVo vo) {
        String key = getKey(vo.getUrl());
        redisTemplate2.opsForValue().set(key, JSONObject.toJSONString(vo.getValue()), 1, TimeUnit.DAYS);
    }

    private String getKey(String url) {
        UserVO userVO = UserVoConstextHolder.getUserVo();
        StringBuilder sb = new StringBuilder(MagicConstant.USER_SHOP_DATA);
        sb.append(url).append("_").append(userVO.getUserId());
        return sb.toString();
    }
}
